package coupon_distribution

import (
	"bp/internal/render"
	"bp/internal/service/param"
	"bp/internal/util"
	couponDistributionGrpc "bp/rpc/gen/webapi/coupon_distribution"
	"context"
)

func (s *CouponDistributionWebApiImp) GetCouponDistribution(ctx context.Context, req *couponDistributionGrpc.GetCouponDistributionReq) (res *couponDistributionGrpc.GetCouponDistributionRes, err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	slog.Infof("coupon_distribution_imp/query.GetCouponDistribution=>%+v", req)
	defer render.FriendlyEntityError(&err, EntityName)
	res = &couponDistributionGrpc.GetCouponDistributionRes{}
	q := s.dao.Q

	couponID, err := s.VldGetCouponDistributionReq(ctx, q, req)
	if err != nil {
		return
	}

	couponDistributionPtr, err := s.entityHub.CouponService.GetCouponDistributionPtr(ctx, q, couponID)
	if err != nil {
		return
	}

	res.CouponDistribution = s.ConvCouponDistributionPtrEntityToPb()(couponDistributionPtr)
	return
}

func (s *CouponDistributionWebApiImp) ListCouponDistributions(ctx context.Context, req *couponDistributionGrpc.ListCouponDistributionsReq) (res *couponDistributionGrpc.ListCouponDistributionsRes, err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	slog.Infof("coupon_distribution_imp/query.ListCouponDistributions=>%+v", req)
	defer render.FriendlyEntityError(&err, EntityName)
	res = &couponDistributionGrpc.ListCouponDistributionsRes{}
	q := s.dao.Q

	cPtr := param.GenListCommonParamFromContext(ctx)
	ptr, err := s.VldListCouponDistributionsReq(ctx, q, req)
	if err != nil {
		return
	}
	total, couponDistributionPtrs, err := s.entityHub.CouponService.ListCouponDistributionPtrs(ctx, q, cPtr, ptr)
	if err != nil {
		return
	}

	res.Total = int32(total)
	res.Rows = s.ConvCouponDistributionPtrArrayEntityToPb()(couponDistributionPtrs)
	return
}

func (s *CouponDistributionWebApiImp) ListCouponDistributionWithStats(ctx context.Context, req *couponDistributionGrpc.ListCouponDistributionWithStatsReq) (res *couponDistributionGrpc.ListCouponDistributionWithStatsRes, err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	slog.Infof("coupon_distribution_imp/query.ListCouponDistributionWithStats=>%+v", req)
	defer render.FriendlyEntityError(&err, EntityName)
	res = &couponDistributionGrpc.ListCouponDistributionWithStatsRes{}
	q := s.dao.Q
	cPtr := param.GenListCommonParamFromContext(ctx)
	ptr, err := s.VldListCouponDistributionWithStatsReq(ctx, q, req)
	if err != nil {
		return
	}
	total, couponDistributionWithStatPtrs, err := s.entityHub.CouponService.ListCouponDistributionWithStatPtrs(ctx, q, cPtr, ptr)
	if err != nil {
		return
	}

	res.Total = int32(total)
	res.Rows = s.ConvCouponDistributionWithStatPtrArrayEntityToPb()(couponDistributionWithStatPtrs)
	return
}
